﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Windows.Forms;
using LogLib;

namespace ComLib.ComFun
{
    public static class AsyncTask
    {
         /// <summary>
        /// 开始一个延时任务
        /// </summary>
        /// <param name="DelayTime">延时时长（秒）</param>
        /// <param name="taskEndAction">延时时间完毕之后执行的委托（会跳转回UI线程）</param>
        /// <param name="control">UI线程的控件</param>
        public static void Delay(int DelayTime, Action taskEndAction)
        {            
            Task task = new Task(() => {
                try
                {
                    Thread.Sleep(DelayTime * 1000);
                    //返回UI线程
                    taskEndAction();
                }
                catch
                {
                    
                }
            }); 
            task.Start();
        }

        /// <summary>
        /// 开始一个延时任务
        /// </summary>
        /// <param name="DelayTime">延时时长（秒）</param>
        /// <param name="taskEndAction">延时时间完毕之后执行的委托（会跳转回UI线程）</param>
        /// <param name="control">UI线程的控件</param>
        public static void StartDelayTask(int DelayTime, Action taskEndAction, Control control)
        {
            if (control == null)
            {
                return;
            }
            Task task = new Task(() => {
                try
                {
                    Thread.Sleep(DelayTime * 1000);
                    //返回UI线程
                    control.Invoke(taskEndAction);
                }
                catch (Exception e)
                {
                    Log.WriteExceptionAsync(e.ToString());
                }
            });
            task.Start();
        }
    }
}
